import axios, {AxiosRequestConfig, AxiosResponse} from "axios";

export interface HttpResult<T> {
    code: number,
    msg: string
    data: T
}

const instance = axios.create({
    baseURL: '/api',
    timeout: 30000
})
instance.interceptors.request.use(config => {
    return config;
}, error => {
    // 处理网络请求状态码
    return Promise.reject(error)
})
instance.interceptors.response.use((resp: AxiosResponse) => {
    // 处理服务器返回状态码
    return resp.data;
}, error => {
    return Promise.reject(error)
})

const requests = {
    get: <T>(url: string, params?: any, config?: AxiosRequestConfig) => {
        return instance<any, HttpResult<T>>({
            url,
            method: "get",
            params,
            ...config
        })
    },
    post: <T>(url: string, data?: any, config?: AxiosRequestConfig) => {
        return instance<any, HttpResult<T>>({
            url,
            method: "post",
            data,
            ...config
        })
    },
    put: <T>(url: string, data?: any, config?: AxiosRequestConfig) => {
        return instance<any, HttpResult<T>>({
            url,
            method: "put",
            data,
            ...config
        })
    },
    delete: <T>(url: string, data?: any, config?: AxiosRequestConfig) => {
        return instance<any, HttpResult<T>>({
            url,
            method: "delete",
            data,
            ...config
        })
    }
}
export default requests;
